package cn.ibizlab.eam.core.extensions.service;

import cn.ibizlab.eam.core.eam_core.domain.*;
import cn.ibizlab.eam.core.eam_core.filter.EMStockSearchContext;
import cn.ibizlab.eam.core.eam_core.service.*;
import cn.ibizlab.eam.core.eam_core.service.impl.EMItemPUseServiceImpl;
import cn.ibizlab.eam.core.util.helper.Aops;
import cn.ibizlab.eam.util.dict.StaticDict;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Primary;

import java.sql.Timestamp;
import java.util.*;
import static java.math.RoundingMode.HALF_UP;

/**
 * 实体[领料单] 自定义服务对象
 */
@Slf4j
@Primary
@Service("EMItemPUseExService")
public class EMItemPUseExService extends EMItemPUseServiceImpl {

    @Autowired
    private IEMItemTradeService iemItemTradeService;

    @Autowired
    private IEMStockService iemStockService;

    @Autowired
    private IEMItemROutService iemItemROutService;

    @Override
    protected Class currentModelClass() {
        return com.baomidou.mybatisplus.core.toolkit.ReflectionKit.getSuperClassGenericType(this.getClass().getSuperclass(), 1);
    }


    @Override
    public boolean create(EMItemPUse et) {
        // 实发数
        if (et.getPsum() == null) {
            et.setPsum(et.getAsum());
        }
        // 领料人
        if (et.getEmpid() == null) {
            et.setEmpid(et.getAempid());
            et.setEmpname(et.getAempname());
        }
        // 总金额
        if (et.getAmount() == null && et.getPsum() != null && et.getPrice() != null) {
            Double amount = NumberUtils.toScaledBigDecimal(et.getPsum() * et.getPrice(), 2, HALF_UP).doubleValue();
            et.setAmount(amount);
        }
        return super.create(et);
    }

    /**
     * 自定义行为[Issue]用户扩展
     *
     * @param et
     * @return
     */
    @Override
    @Transactional
    public EMItemPUse issue(EMItemPUse et) {
        // EMItemPUse（领料单）确认发料
        et = this.get(et.getEmitempuseid());
        if (et == null) {
            throw new RuntimeException("领料单不存在，无法执行操作");
        }
        EMItemTrade emItemTrade = iemItemTradeService.get(et.getEmitempuseid());
        issuePuse(et, emItemTrade);
        // 流程步骤WFSTEP置空，
        et.setWfstep(null);
        // 领料单状态PUSESTATE变为“已发料”20，
        et.setPusestate(StaticDict.EMPUSESTATE.ITEM_20.getValue());
        et.setWfstate(Integer.valueOf(StaticDict.WFStates.ITEM_2.getValue()));
        Aops.getSelf(this).update(et);

        emItemTrade.setTradestate(Integer.valueOf(StaticDict.EMTRADESTATE.ITEM_20.getValue()));
        iemItemTradeService.update(emItemTrade);
        return super.issue(et);
    }

    /**
     * 确认发料的行为，比较并修改库存、产品明细对应的信息
     */
    public void issuePuse(EMItemPUse et, EMItemTrade emItemTrade) {

        //-------------初始化单据参数
        String varOrgid = et.getOrgid();
        String varEmitemtraderId = emItemTrade.getEmitemtradeid();
        String varItemId = emItemTrade.getItemid();
        Double varPrice = emItemTrade.getPrice();
        Double varAmount = emItemTrade.getAmount();
        Double varPsum = emItemTrade.getPsum();
        String varBatcode = emItemTrade.getBatcode();
        String varStoreId = emItemTrade.getStoreid();
        String varStorepartId = emItemTrade.getStorepartid();
        Integer varInoutFlag = emItemTrade.getInoutflag();
        Timestamp varSdate = emItemTrade.getSdate();
        String varAempId = emItemTrade.getAempid();
        String varexOrgid = emItemTrade.getOrgid();
        Double varChangeAmount = null;

        //修改总金额
        //领料表
        et.setAmount(NumberUtils.toScaledBigDecimal(et.getPrice() * et.getPsum(), 2, HALF_UP).doubleValue());
        //物品交易表
        emItemTrade.setAmount(NumberUtils.toScaledBigDecimal(et.getPrice() * et.getPsum(), 2, HALF_UP).doubleValue());

        if (emItemTrade == null) {
            throw new RuntimeException("未找到已确认的收支单据，无法完成操作");
        }
        //如果组织为空，默认是上海港
        if (varOrgid == null) {
            emItemTrade.setOrgid(StaticDict.PFCL_ORG.TIP.getValue());
        }
        //批次为空，默认是NA
        if (varBatcode == null) {
            emItemTrade.setBatcode("NA");
        }

        //----------- 初始化物品参数
        EMItem emItem = emitemService.get(emItemTrade.getItemid());
        //库存量
        Double varItemcnt = emItem.getStocksum();
        //库存金额
        Double varItemAmount = emItem.getAmount();
        //平均价
        Double varItemPrice = emItem.getPrice();

        if (emItem == null) {
            throw new RuntimeException("未找到已确认的物品信息，无法完成操作");
        }
        //初始化，库存和库存金额为空，默认为0
        if (varItemcnt == null) {
            emItem.setStocksum(0.0);
        }
        if (varItemAmount == null) {
            emItem.setAmount(0.0);
        }

        //--------------变更物品均价，总库存，总库存金额
        //varPsum实领数
        varItemcnt -= varPsum;
        if (varItemcnt == 0) {
            varChangeAmount = varItemAmount;
        }
        //varAmount总金额
        varItemAmount -= varAmount;

        if (varItemcnt == null) {
            varItemAmount = 0.0;
        } else {
            varItemPrice = NumberUtils.toScaledBigDecimal(varItemAmount / varItemcnt, 2, HALF_UP).doubleValue();
        }
        if (varItemcnt < 0) {
            throw new RuntimeException("物品总库存不够，无法完成操作");
        }

        //--------------初始化库存明细参数
        EMStockSearchContext ctx = new EMStockSearchContext();
        ctx.setN_itemid_eq(varItemId);
        ctx.setN_storeid_eq(varStoreId);
        ctx.setN_storepartid_eq(varStorepartId);
        ctx.setSize(1);
        List<EMStock> emStocks = iemStockService.searchDefault(ctx).getContent();
        if (emStocks==null||emStocks.isEmpty()){
            throw new RuntimeException("未找到对应的库存信息，无法完成操作");
        }
        EMStock emStock = emStocks.get(0);
        //库存数量
        Double varStockcnt = emStock.getStockcnt();

        //--------------变更库存明细总库存
        varStockcnt -= varPsum;
        if (varStockcnt < 0) {
            throw new RuntimeException("当前仓库物品库存不够，无法完成操作");
        }

        //修改库存数量
        emStock.setStockcnt(varStockcnt);
        emStock.setUpdateman(et.getUpdateman());
        iemStockService.update(emStock);

        //----------------库存为0 删除库存记录
        if (varStockcnt == 0) {
            iemStockService.remove(emStock.getEmstockid());
        }

        //----------------出空原则，更新出库金额
        List<EMItemROut> emItemROuts = iemItemROutService.selectByItemid(emItem.getEmitemid());
        //varStockcnt 库存量
        if (varStockcnt == 0) {
            emItemTrade.setAmount(varChangeAmount);
            iemItemTradeService.update(emItemTrade);
            et.setAmount(varChangeAmount);
            Aops.getSelf(this).update(et);
        } else {
            varStockcnt = varPsum;
            if (varStockcnt < 0) {
                throw new RuntimeException("当前仓库物品库存不够，无法完成操作");
            }
        }

        EMStock stock = new EMStock();
        stock.setBatcode(varBatcode);
        stock.setItemid(varItemId);
        stock.setOrgid(varexOrgid);
        stock.setStoreid(varStoreId);
        stock.setStorepartid(varStorepartId);
        iemStockService.create(stock);

        //---------------初始化物品参数
        double varShfamount = emItemTrade.getShf() != null ? emItemTrade.getShf() : 0;
        double varShfsum = emItemTrade.getPsum() != null ? emItemTrade.getPsum() : 0;
        double varShfprice = 0;
        if (varShfsum > 0) {
            varShfprice = Math.round(varShfamount / varShfsum);
        }
        //------------变更物品均价，总库存，总库存金额

        emItem.setStocksum(varItemcnt);
        emItem.setPrice(varItemPrice);
        emItem.setAmount(varItemAmount);
        emItem.setStoreid(varStoreId);
        emItem.setStorepartid(varStorepartId);
        emItem.setShfprice(varShfprice);
        emitemService.update(emItem);

    }
}

